class Export

	def Export.filename_format(f)
		str = f.sub(' ', '_').downcase
		begin
			str = Iconv.conv('iso-8859-1', 'utf-8', str)
		rescue; end
		return str
	end

	def Export.export_txt(book, path, type, line_ending, encoding)
		chapters = []
		book.chapters.each_index { |i| chapters[i] = '' }

		i = 0
		book.chapters.each do |chapter|
			chapters[i] += chapter.name.upcase + "\n"
			1.upto(chapter.name.length) { |x| chapters[i] += '-' }
			chapters[i] += "\n\n"
			chapter.text.each do |text_block|
				chapters[i] += text_block if text_block.kind_of? String
			end
			chapters[i] += "\n\n\n" if type == :one_file
			i += 1 if type == :many_files
		end

		chapters.each do |chapter|
			chapter.replace(Iconv.conv('iso-8859-1', 'utf-8', chapter)) if encoding == :latin1
		end

		def Export.put_byte(file, byte, line_ending)
			if byte == 10
				case line_ending
				when :windows
					file.putc 13
					file.putc 10
				when :unix
					file.putc 13
				when :mac
					file.putc 10
				end
			else
				file.putc byte
			end
		end

		if type == :one_file
			f = File.open(path + '/' + Export.filename_format(book.title) + '.txt', 'wb')
			chapters[0].each_byte { |byte| Export.put_byte(f, byte, line_ending) }
			f.close
		else
			i = 0
			book.chapters.each do |chapter|
				f = File.open(path + '/' + Export.filename_format(chapter.name) + '.txt', 'wb')
				chapters[i].each_byte { |byte| Export.put_byte(f, byte, line_ending) }
				f.close
				i += 1
			end
		end
		
	end

end
